package com.yuyou.weixin.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.yuyou.weixin.bean.ReturnResult;
import com.yuyou.weixin.cache.FnGuavaCacheUtil;
import com.yuyou.weixin.entity.FnWxSrsActivity;
import com.yuyou.weixin.entity.FnWxSrsActivityUserRelation;
import com.yuyou.weixin.entity.FnWxSrsUser;
import com.yuyou.weixin.enums.ActivityEnums;
import com.yuyou.weixin.mapper.FnWxSrsActivityMapper;
import com.yuyou.weixin.service.IFnWxSrsActivityService;
import com.yuyou.weixin.service.IFnWxSrsActivityUserRelationService;
import com.yuyou.weixin.service.IFnWxSrsUserService;
import com.yuyou.weixin.util.Sequence;
import com.yuyou.weixin.vo.resp.ActivityDetail;
import com.yuyou.weixin.vo.resp.AssistanceResult;
import com.yuyou.weixin.vo.resp.AssistanceUser;

//@Service
public class FnWxSrsActivityServiceImpl implements IFnWxSrsActivityService {

    @Autowired
    private FnWxSrsActivityMapper mapper;

    @Autowired
    private IFnWxSrsUserService fnWxSrsUserService;

    @Autowired
    private IFnWxSrsActivityUserRelationService fnWxSrsActivityUserRelationService;

    private static final String maxCode = "MAX_EXCLUSIVE_CODE";

    @Value("${fn.active.count}")
    private Integer activeCount;


    @Override
    public int deleteByPrimaryKey(Long id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(FnWxSrsActivity record) {
        return mapper.insert(record);
    }

    @Override
    public FnWxSrsActivity selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(FnWxSrsActivity record) {
        return mapper.updateByPrimaryKeySelective(record);
    }

    @Override
    @Transactional
    public ReturnResult<AssistanceResult> assistance(String projectCode, String openId, int exclusiveCode, String headImg, String name) {
        //助力者个人活动
        AssistanceResult ar = new AssistanceResult();
        FnWxSrsUser user = fnWxSrsUserService.selectByOpenId(openId , projectCode);
        if(user == null){//新用户
            String newExclusiveCode = FnGuavaCacheUtil.get(FnWxSrsActivityServiceImpl.maxCode);
            if(StringUtils.isEmpty(newExclusiveCode)){
                newExclusiveCode = fnWxSrsUserService.getMaxExclusiveCode(projectCode);
                if(StringUtils.isEmpty(newExclusiveCode)){newExclusiveCode = "1000";}

            }
            Integer exclusiveCodeInt = Integer.valueOf(newExclusiveCode) + 1;
            FnGuavaCacheUtil.put(FnWxSrsActivityServiceImpl.maxCode , exclusiveCodeInt+"");
            user = new FnWxSrsUser();
            user.setName(name);
            user.setHeadImg(headImg);
            user.setOpenId(openId);
            user.setCreateTime(new Date());
            user.setId(Sequence.getSequence().nextId());
            user.setExclusiveCode(Integer.valueOf(exclusiveCodeInt));
            fnWxSrsUserService.insert(user);

        }else{
            user.setHeadImg(headImg);
            user.setName(name);
            fnWxSrsUserService.updateByPrimaryKeySelective(user);
        }
        FnWxSrsActivity activity = saveOrGetByUser(user);
        ar.setMediaId(activity.getMediaId());
        ar.setExclusiveCode(user.getExclusiveCode());

        //被助力者部分
        String assistanceResult = checkassistance(exclusiveCode , user);
        ar.setAssistanceResult(assistanceResult);
        return ReturnResult.success(ar);
    }

    @Override
    @Transactional
    public void updateMediaId(String openId, String projectCode, String mediaId) {
        FnWxSrsUser user = fnWxSrsUserService.selectByOpenId(openId , projectCode);
        if(user == null){return;}
        FnWxSrsActivity activity = mapper.selectByUserId(user.getId() , user.getProjectCode());
        if(activity == null){return;}
        activity.setMediaId(mediaId);
    }

    @Override
    public ActivityDetail getActivityDetail(Long activityId, String projectCode) {
        ActivityDetail ad = new ActivityDetail();

        FnWxSrsActivity activity = selectByPrimaryKey(activityId);
        if(activity == null){
            return null;
        }
        FnWxSrsUser user = fnWxSrsUserService.selectByPrimaryKey(activity.getFnWxSrsUserId());
        if(user == null){
            return null;
        }
        ad.setStatus(activity.getStatus());
        ad.setOpenId(user.getOpenId());
        ad.setHead_img(user.getHeadImg());
        ad.setName(user.getName());

        List<AssistanceUser> assistanceUsers = fnWxSrsActivityUserRelationService.getAssistanceUser(activityId);
        ad.setAssistanceUsers(assistanceUsers);

        if(activeCount != null && assistanceUsers.size() >= activeCount){//已达标或已领奖
            ad.setReach(assistanceUsers.get(activeCount-1).getAssistanceTime());//达标时间
        }
        return ad;
    }

    public FnWxSrsActivity saveOrGetByUser(FnWxSrsUser user){
        FnWxSrsActivity activity = mapper.selectByUserId(user.getId() , user.getProjectCode());
        if(activity == null){
            activity = new FnWxSrsActivity();
            activity.setCreateTime(new Date());
            activity.setExclusiveCode(user.getExclusiveCode());
            activity.setFnWxSrsUserId(user.getId());
            activity.setId(Sequence.getSequence().nextId());
            activity.setStatus(ActivityEnums.status.init.getValue());
            activity.setProjectCode(user.getProjectCode());
            activity.setMediaId(null);//第一次创建无微信图片id
            insert(activity);

            //插入关系图
            FnWxSrsActivityUserRelation relation = new FnWxSrsActivityUserRelation();
            relation.setCreateTime(new Date());
            relation.setFnWxSrsActivityId(activity.getId());
            relation.setFnWxSrsUserId(user.getId());
            relation.setProjectCode(user.getProjectCode());
            relation.setId(Sequence.getSequence().nextId());
            fnWxSrsActivityUserRelationService.insert(relation);
        }

        return activity;
    }


    public String checkassistance(Integer exclusiveCode , FnWxSrsUser user){
        String assistanceResult;
        FnWxSrsActivity activitied = mapper.selectByCode(exclusiveCode , user.getProjectCode());
        if(activitied == null){
            assistanceResult = "";
        }else{
            if(activitied.getFnWxSrsUserId().equals(user.getId())){//自己助力自己
                return "助力失败，不能自己为自己助力，可通过分享海报让好友来助您一臂之力哦～";
            }

            //插入关系图
            FnWxSrsActivityUserRelation relation = new FnWxSrsActivityUserRelation();
            relation.setCreateTime(new Date());
            relation.setFnWxSrsActivityId(activitied.getId());
            relation.setFnWxSrsUserId(user.getId());
            relation.setProjectCode(user.getProjectCode());
            relation.setId(Sequence.getSequence().nextId());
            fnWxSrsActivityUserRelationService.insert(relation);

            Integer assistanceCount = mapper.checkAssistance(activitied.getId() , user.getProjectCode());
            if(activeCount == assistanceCount){//助力完成
                activitied.setStatus(ActivityEnums.status.finish.getValue());
                mapper.updateByPrimaryKeySelective(activitied);
            }

            assistanceResult = "";
        }
        return  assistanceResult;
    }


}